"""
用户管理API
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.user import User
from app.utils.decorators import validate_json, admin_required, validate_pagination
from app.utils.validators import validate_user_data, validate_email, validate_username, validate_password
from marshmallow import ValidationError

users_bp = Blueprint('users', __name__)

@users_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户资料"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户资料失败: {str(e)}'}), 500

@users_bp.route('/profile', methods=['PUT'])
@jwt_required()
@validate_json(['first_name', 'last_name', 'email'])
def update_profile():
    """更新用户资料"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 更新用户信息
        if 'first_name' in data:
            user.first_name = data['first_name']
        if 'last_name' in data:
            user.last_name = data['last_name']
        if 'email' in data:
            # 检查邮箱是否已被其他用户使用
            existing_user = User.find_by_email(data['email'])
            if existing_user and existing_user.id != current_user_id:
                return jsonify({'error': '邮箱已被其他用户使用'}), 400
            user.email = data['email']
        
        db.session.commit()
        
        return jsonify({
            'message': '用户资料更新成功',
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新用户资料失败: {str(e)}'}), 500

@users_bp.route('/change-password', methods=['POST'])
@jwt_required()
@validate_json(['current_password', 'new_password'])
def change_password():
    """修改密码"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        current_password = data['current_password']
        new_password = data['new_password']
        
        # 验证当前密码
        if not user.check_password(current_password):
            return jsonify({'error': '当前密码错误'}), 400
        
        # 设置新密码
        user.set_password(new_password)
        db.session.commit()
        
        return jsonify({
            'message': '密码修改成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'修改密码失败: {str(e)}'}), 500

@users_bp.route('/', methods=['GET'])
@jwt_required()
def get_users():
    """获取用户列表"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.find_by_id(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取所有用户（简化版本，实际应该根据权限过滤）
        users = User.query.all()
        
        return jsonify({
            'users': [user.to_dict() for user in users]
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户列表失败: {str(e)}'}), 500

@users_bp.route('/stats', methods=['GET'])
@jwt_required()
def get_user_stats():
    """获取用户统计信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户的任务统计
        from app.models.task import Task, TaskStatus
        tasks = Task.query.filter_by(assignee_id=current_user_id).all()
        
        total_tasks = len(tasks)
        completed_tasks = len([t for t in tasks if t.status == TaskStatus.DONE])
        in_progress_tasks = len([t for t in tasks if t.status == TaskStatus.IN_PROGRESS])
        todo_tasks = len([t for t in tasks if t.status == TaskStatus.TODO])
        
        # 获取用户的项目统计
        from app.models.project import Project
        projects = Project.query.filter_by(owner_id=current_user_id).all()
        
        # 获取用户加入的团队统计
        from app.models.team import TeamMember
        teams = TeamMember.query.filter_by(user_id=current_user_id).all()
        
        stats = {
            'tasks': {
                'total': total_tasks,
                'completed': completed_tasks,
                'in_progress': in_progress_tasks,
                'todo': todo_tasks,
                'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
            },
            'projects': {
                'owned': len(projects),
                'total': len(projects)
            },
            'teams': {
                'joined': len(teams)
            }
        }
        
        return jsonify({
            'stats': stats
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户统计失败: {str(e)}'}), 500


# ==================== 管理员专用功能 ====================

@users_bp.route('/admin', methods=['GET'])
@jwt_required()
@admin_required
@validate_pagination
def get_all_users():
    """获取所有用户列表（管理员专用）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '', type=str)
        status = request.args.get('status', '', type=str)  # active, inactive, all
        
        # 构建查询
        query = User.query
        
        # 搜索过滤
        if search:
            query = query.filter(
                db.or_(
                    User.username.contains(search),
                    User.email.contains(search),
                    User.first_name.contains(search),
                    User.last_name.contains(search)
                )
            )
        
        # 状态过滤
        if status == 'active':
            query = query.filter_by(is_active=True)
        elif status == 'inactive':
            query = query.filter_by(is_active=False)
        
        # 分页
        users = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        return jsonify({
            'users': [user.to_dict() for user in users.items],
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': users.total,
                'pages': users.pages,
                'has_next': users.has_next,
                'has_prev': users.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户列表失败: {str(e)}'}), 500


@users_bp.route('/admin/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_user_by_id(user_id):
    """获取指定用户详情（管理员专用）"""
    try:
        user = User.find_by_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户的详细统计信息
        from app.models.task import Task, TaskStatus
        from app.models.project import Project
        from app.models.team import TeamMember
        
        # 任务统计
        tasks = Task.query.filter_by(assignee_id=user_id).all()
        total_tasks = len(tasks)
        completed_tasks = len([t for t in tasks if t.status == TaskStatus.DONE])
        
        # 项目统计
        owned_projects = Project.query.filter_by(owner_id=user_id).all()
        
        # 团队统计
        team_memberships = TeamMember.query.filter_by(user_id=user_id).all()
        
        user_data = user.to_dict()
        user_data['stats'] = {
            'tasks': {
                'total': total_tasks,
                'completed': completed_tasks,
                'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
            },
            'projects': {
                'owned': len(owned_projects)
            },
            'teams': {
                'joined': len(team_memberships)
            }
        }
        
        return jsonify({
            'user': user_data
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户详情失败: {str(e)}'}), 500


@users_bp.route('/admin', methods=['POST'])
@jwt_required()
@admin_required
@validate_json(['username', 'email', 'password'])
def create_user():
    """创建新用户（管理员专用）"""
    try:
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_user_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 检查用户名是否已存在
        if User.find_by_username(validated_data['username']):
            return jsonify({'error': '用户名已存在'}), 400
        
        # 检查邮箱是否已存在
        if User.find_by_email(validated_data['email']):
            return jsonify({'error': '邮箱已存在'}), 400
        
        # 创建用户
        user = User(
            username=validated_data['username'],
            email=validated_data['email'],
            first_name=validated_data.get('first_name', ''),
            last_name=validated_data.get('last_name', ''),
            is_active=validated_data.get('is_active', True),
            is_admin=validated_data.get('is_admin', False)
        )
        user.set_password(validated_data['password'])
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'message': '用户创建成功',
            'user': user.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建用户失败: {str(e)}'}), 500


@users_bp.route('/admin/<int:user_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_user(user_id):
    """更新用户信息（管理员专用）"""
    try:
        user = User.find_by_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_user_data(data, is_update=True)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 更新用户信息
        if 'username' in validated_data:
            # 检查用户名是否已被其他用户使用
            existing_user = User.find_by_username(validated_data['username'])
            if existing_user and existing_user.id != user_id:
                return jsonify({'error': '用户名已被其他用户使用'}), 400
            user.username = validated_data['username']
        
        if 'email' in validated_data:
            # 检查邮箱是否已被其他用户使用
            existing_user = User.find_by_email(validated_data['email'])
            if existing_user and existing_user.id != user_id:
                return jsonify({'error': '邮箱已被其他用户使用'}), 400
            user.email = validated_data['email']
        
        if 'first_name' in validated_data:
            user.first_name = validated_data['first_name']
        
        if 'last_name' in validated_data:
            user.last_name = validated_data['last_name']
        
        if 'is_active' in validated_data:
            user.is_active = validated_data['is_active']
        
        if 'is_admin' in validated_data:
            user.is_admin = validated_data['is_admin']
        
        # 更新密码（如果提供）
        if 'password' in validated_data and validated_data['password']:
            user.set_password(validated_data['password'])
        
        db.session.commit()
        
        return jsonify({
            'message': '用户更新成功',
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新用户失败: {str(e)}'}), 500


@users_bp.route('/admin/<int:user_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_user(user_id):
    """删除用户（管理员专用）"""
    try:
        current_user_id = get_jwt_identity()
        
        # 不能删除自己
        if user_id == current_user_id:
            return jsonify({'error': '不能删除自己的账户'}), 400
        
        user = User.find_by_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 检查用户是否有未完成的任务或项目
        from app.models.task import Task
        from app.models.project import Project
        
        active_tasks = Task.query.filter_by(assignee_id=user_id).filter(
            Task.status.in_(['todo', 'in_progress', 'review'])
        ).count()
        
        owned_projects = Project.query.filter_by(owner_id=user_id).count()
        
        if active_tasks > 0:
            return jsonify({'error': f'用户有 {active_tasks} 个未完成的任务，无法删除'}), 400
        
        if owned_projects > 0:
            return jsonify({'error': f'用户拥有 {owned_projects} 个项目，无法删除'}), 400
        
        # 删除用户
        db.session.delete(user)
        db.session.commit()
        
        return jsonify({
            'message': '用户删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除用户失败: {str(e)}'}), 500


@users_bp.route('/admin/<int:user_id>/toggle-status', methods=['POST'])
@jwt_required()
@admin_required
def toggle_user_status(user_id):
    """切换用户状态（激活/停用）"""
    try:
        current_user_id = get_jwt_identity()
        
        # 不能停用自己
        if user_id == current_user_id:
            return jsonify({'error': '不能停用自己的账户'}), 400
        
        user = User.find_by_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 切换状态
        user.is_active = not user.is_active
        db.session.commit()
        
        status = '激活' if user.is_active else '停用'
        
        return jsonify({
            'message': f'用户已{status}',
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'切换用户状态失败: {str(e)}'}), 500


@users_bp.route('/admin/<int:user_id>/reset-password', methods=['POST'])
@jwt_required()
@admin_required
@validate_json(['new_password'])
def reset_user_password(user_id):
    """重置用户密码（管理员专用）"""
    try:
        user = User.find_by_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        new_password = data['new_password']
        
        # 验证新密码
        if not validate_password(new_password):
            return jsonify({'error': '密码必须至少8位，包含字母和数字'}), 400
        
        # 设置新密码
        user.set_password(new_password)
        db.session.commit()
        
        return jsonify({
            'message': '密码重置成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'重置密码失败: {str(e)}'}), 500


@users_bp.route('/admin/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_admin_stats():
    """获取管理员统计信息"""
    try:
        from app.models.task import Task, TaskStatus
        from app.models.project import Project
        from app.models.team import Team
        
        # 用户统计
        total_users = User.query.count()
        active_users = User.query.filter_by(is_active=True).count()
        admin_users = User.query.filter_by(is_admin=True).count()
        
        # 任务统计
        total_tasks = Task.query.count()
        completed_tasks = Task.query.filter_by(status=TaskStatus.DONE).count()
        
        # 项目统计
        total_projects = Project.query.count()
        active_projects = Project.query.filter_by(is_active=True).count()
        
        # 团队统计
        total_teams = Team.query.count()
        
        # 最近注册的用户
        recent_users = User.query.order_by(User.created_at.desc()).limit(5).all()
        
        stats = {
            'users': {
                'total': total_users,
                'active': active_users,
                'inactive': total_users - active_users,
                'admins': admin_users
            },
            'tasks': {
                'total': total_tasks,
                'completed': completed_tasks,
                'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
            },
            'projects': {
                'total': total_projects,
                'active': active_projects
            },
            'teams': {
                'total': total_teams
            },
            'recent_users': [user.to_dict() for user in recent_users]
        }
        
        return jsonify({
            'stats': stats
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取统计信息失败: {str(e)}'}), 500


# ==================== 用户设置功能 ====================

@users_bp.route('/settings', methods=['GET'])
@jwt_required()
def get_user_settings():
    """获取用户设置"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        settings = user.get_settings()
        
        return jsonify({
            'settings': settings
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户设置失败: {str(e)}'}), 500


@users_bp.route('/settings', methods=['PUT'])
@jwt_required()
def update_user_settings():
    """更新用户设置"""
    try:
        current_user_id = get_jwt_identity()
        user = User.find_by_id(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        if not data:
            return jsonify({'error': '请求数据不能为空'}), 400
        
        # 验证设置数据
        valid_settings = {}
        allowed_settings = {
            # 通知设置
            'taskNotifications': bool,
            'projectNotifications': bool,
            'teamNotifications': bool,
            'emailNotifications': bool,
            # 隐私设置
            'publicProfile': bool,
            'showOnlineStatus': bool,
            # 外观设置
            'theme': str,
            'language': str,
            # 常规设置
            'timezone': str,
            'dateFormat': str,
            'timeFormat': str,
        }
        
        for key, value in data.items():
            if key in allowed_settings:
                expected_type = allowed_settings[key]
                if isinstance(value, expected_type):
                    valid_settings[key] = value
                else:
                    return jsonify({'error': f'设置 {key} 的值类型不正确'}), 400
        
        # 验证特定设置值
        if 'theme' in valid_settings and valid_settings['theme'] not in ['light', 'dark', 'auto']:
            return jsonify({'error': '主题设置值无效'}), 400
        
        if 'language' in valid_settings and valid_settings['language'] not in ['zh-CN', 'en-US']:
            return jsonify({'error': '语言设置值无效'}), 400
        
        if 'timeFormat' in valid_settings and valid_settings['timeFormat'] not in ['12h', '24h']:
            return jsonify({'error': '时间格式设置值无效'}), 400
        
        # 更新设置
        user.update_settings(valid_settings)
        
        return jsonify({
            'message': '设置更新成功',
            'settings': user.get_settings()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新用户设置失败: {str(e)}'}), 500
